package com.sunlands.com.commands;

import com.netflix.hystrix.*;
import com.sunlands.com.service.WechatRpcService;
import rx.Observable;
import rx.Subscriber;
import rx.schedulers.Schedulers;

/**
 * Created by yusong on 2018/5/18.
 * 企业微信发消息命令
 */
public class WechatObservableCommand extends HystrixObservableCommand<String> {

    /**
     * cache the Setter
     */
    private static final HystrixCommandGroupKey groupKey = HystrixCommandGroupKey.Factory.asKey("WechatRpc");

    private String email;
    private String content;

    public WechatObservableCommand(String email,String content) {
        super(HystrixObservableCommand.Setter.withGroupKey(groupKey)
        );
        this.email = email;
        this.content = content;
    }

    @Override
    protected Observable<String> construct() {
        return Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> observer) {
                try {
                    //正常逻辑
                    observer.onNext("任务开始了");
                    try {
                        Thread.sleep(1500);
                        String res = WechatRpcService.sendMsg(email,content);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    observer.onNext("aaa");
                    //任务结束了
                    observer.onCompleted();
                } catch (Exception e) {
                    //异常的话怎么处理？
                    observer.onError(e);
                }
            }
        }).subscribeOn(Schedulers.io());
    }
}